package com.tool.minio.service.impl;

import com.tool.minio.service.MinioService;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author 酒徒
 * @Version 1.0
 * @data 2025/6/19 15:41
 */
@Service
public class MinioServiceImpl implements MinioService {
    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucket;

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        String objectName = generateRandomFilename(file);

        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucket)
                        .object(objectName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
        return minioClient.getPresignedObjectUrl(
                GetPresignedObjectUrlArgs.builder() // 使用构建器直接创建参数
                        .method(Method.GET)         // 必须指定HTTP方法
                        .bucket(bucket)
                        .object(objectName)
                        .build()).split("\\?")[0];
    }

    // 新增方法：生成随机文件名（带原始文件扩展名）
    public String generateRandomFilename(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String extension = "";

        // 获取文件扩展名
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        // 生成UUID作为随机文件名
        String randomName = UUID.randomUUID().toString().replace("-", "");

        // 组合成最终文件名：UUID + 扩展名
        return randomName + extension;
    }

}
